package org.dragonnova.meetingapp.core.manager;

import android.text.TextUtils;

import org.dragonnova.meetingapp.model.bean.DeviceInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hucn on 2016/6/16.
 * Description: 用于维护连接的客户端的列表
 */
public class DeviceManager {

    public static Map<String, DeviceInfo> mDeviceInfoes = null;

    private static DeviceManager mDeviceManager;

    private DeviceManager() {
        mDeviceInfoes = Collections.synchronizedMap(new LinkedHashMap<String, DeviceInfo>());
    }

    public static DeviceManager getInstance() {
        if (mDeviceManager == null) {
            synchronized (DeviceManager.class) {
                if (mDeviceManager == null) {
                    mDeviceManager = new DeviceManager();
                }
            }
        }
        return mDeviceManager;
    }

    public boolean equals(DeviceInfo info1, DeviceInfo info2) {
        return TextUtils.equals(info1.getHostId(), info2.getHostId());
    }

    public boolean contains(DeviceInfo info) {
        return mDeviceInfoes.containsKey(info.getHostId());
    }

    public boolean contains(String hostId) {
        return mDeviceInfoes.containsKey(hostId);
    }

    public boolean add(DeviceInfo deviceInfo) {
        if (mDeviceInfoes.containsKey(deviceInfo.getHostId())) {
            return false;
        }
        mDeviceInfoes.put(deviceInfo.getHostId(), deviceInfo);
        return true;
    }

    public boolean update(DeviceInfo deviceInfo) {
        if (!mDeviceInfoes.containsKey(deviceInfo.getHostId())) {
            return false;
        }
        mDeviceInfoes.remove(deviceInfo.getHostId());
        mDeviceInfoes.put(deviceInfo.getHostId(), deviceInfo);
        return true;
    }

    public DeviceInfo getDeviceInfo(String hostId) {
        return mDeviceInfoes.get(hostId);
    }

    public List<DeviceInfo> getAllDeviceInfos() {
        return new ArrayList<>(mDeviceInfoes.values());
    }

    public List<DeviceInfo> getConnettedDeviceInfos() {
        List<DeviceInfo> connectedDeviceInfos = new ArrayList<>();
        for (DeviceInfo info : mDeviceInfoes.values()) {
            if (info.getWifiStatus() == DeviceInfo.Status.Connected) {
                connectedDeviceInfos.add(info);
            }
        }
        return connectedDeviceInfos;
    }

    public boolean remove(DeviceInfo deviceInfo) {
        if (mDeviceInfoes.containsKey(deviceInfo.getHostId())) {
            mDeviceInfoes.remove(deviceInfo.getHostId());
            return true;
        }
        return false;
    }

    public void clear() {
        mDeviceInfoes.clear();
    }

    public void saveDeviceInfos() {

    }

    public void getSavedDeviceInfos() {

    }
}
